package com.zlcx.tz.live.common.thread;

import com.zlcx.tz.live.constant.AppEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

import static com.zlcx.tz.live.common.interceptor.AutoLogAspect.APP;
import static com.zlcx.tz.live.common.interceptor.AutoLogAspect.REQUEST_ID;

public class MdcRunable {
    public static void setRequestIdIfAbsent(String requestId) {
        if (StringUtils.isEmpty(requestId)) {
            MDC.put(REQUEST_ID, UUID.randomUUID().toString().replace("-", ""));
        }else {
            MDC.put(REQUEST_ID, requestId);
        }
    }

    public static void setAppIfAbsent(String app) {
        if (StringUtils.isEmpty(app)) {
            MDC.put(APP, AppEnum.tongzhuo.name());
        }else {
            MDC.put(APP, app);
        }
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setRequestIdIfAbsent(MDC.get(REQUEST_ID));
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {

        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setRequestIdIfAbsent(MDC.get(REQUEST_ID));
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
